/****************************************************
 * Description: ServiceImpl for 服务器信息
 * Copyright:   Copyright (c) 2019
 * Company:     ry
 * @author reywong
 * @version 1.0
 * @see
HISTORY
 *  2019-12-04 reywong Create File
 **************************************************/

package cn.com.ry.framework.application.meteor.meteor.machineinfo.service.impl;

import cn.com.ry.framework.application.meteor.framework.dao.XjjDAO;
import cn.com.ry.framework.application.meteor.framework.exception.ValidationException;
import cn.com.ry.framework.application.meteor.framework.service.XjjServiceSupport;
import cn.com.ry.framework.application.meteor.meteor.machineinfo.dao.MachineinfoDao;
import cn.com.ry.framework.application.meteor.meteor.machineinfo.entity.MachineinfoEntity;
import cn.com.ry.framework.application.meteor.meteor.machineinfo.service.MachineinfoService;
import cn.com.ry.framework.application.meteor.sys.xfile.dao.XfileDao;
import cn.com.ry.framework.application.meteor.sys.xfile.entity.XfileEntity;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class MachineinfoServiceImpl extends XjjServiceSupport<MachineinfoEntity> implements MachineinfoService {

    @Autowired
    private MachineinfoDao machineinfoDao;

    @Autowired
    private XfileDao xfileDao;

    @Override
    public XjjDAO<MachineinfoEntity> getDao() {

        return machineinfoDao;
    }

    /**
     * 导入用户
     *
     * @param fileId
     */
    public Map<String, Object> saveImport(Long fileId) throws ValidationException {
        //校验数据并返回合法数据
        List<MachineinfoEntity> machineinfoEntityList = this.validImport(fileId);
        if (machineinfoEntityList == null || machineinfoEntityList.size() == 0) {
            throw new ValidationException("文件数据为空，请重新上传");
        }
        int troubleMachineinfoCnt = 0;
        int okCnt = 0;
        //保存数据
        for (int i = 0; i < machineinfoEntityList.size(); i++) {
            try {
                MachineinfoEntity machineinfoEntity = machineinfoEntityList.get(i);
                machineinfoDao.save(machineinfoEntity);
            } catch (Exception e) {
                e.printStackTrace();
                throw new ValidationException(e.getMessage());
            }
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("allCnt", machineinfoEntityList.size());
        map.put("troubleMachineinfoCnt", troubleMachineinfoCnt);
        map.put("okCnt", okCnt);
        return map;
    }

    private List<MachineinfoEntity> validImport(Long fileId) throws ValidationException {
        //获得上传文件
        XfileEntity xfile = xfileDao.getById(fileId);
        if (xfile == null) {
            throw new ValidationException("未找到上传文件");
        }
        /**
         * 1.验证上传文件是否为空并且文件格式是否是xls
         */
        String fileName = xfile.getFileRealname();
        String prefix = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        if (!prefix.equals("xls") && !prefix.equals("xlsx")) {
            throw new ValidationException("请上传xls或者xlsx格式的文件");
        }
        String[] content = null;
        Workbook workbook = null;
        Sheet sheet = null;
        int length = 0;
        try {
            File file = new File((xfile.getFilePath()));
            workbook = Workbook.getWorkbook(file);
            sheet = workbook.getSheet(0);
            length = sheet.getRows();
        } catch (Exception ex) {
            throw new ValidationException("文件格式转换异常");
        }
        /**
         * 2.验证上传文件中的Excel
         */

        StringBuilder validationMsg = new StringBuilder();
        Cell cell = null;
        int columns = 1;
        if (sheet != null && sheet.getColumns() < columns) {
            validationMsg.append("上传失败：上传文件中的Excel列数必须是" + columns + "列。<br/>");
        }
        List<MachineinfoEntity> machineinfoEntityList = new ArrayList<MachineinfoEntity>();
        /**
         * 3.验证上传文件中的Excel每一行每一列都不为空
         */
        //TODO
        Long id = null;//id
        for (int i = 1; i < length; i++) {// 第2行开始
            content = new String[sheet.getColumns()];
            for (int j = 0; j < columns; j++) {
                cell = sheet.getCell(j, i);
                content[j] = cell.getContents().trim();
            }
            if (content[0] == null || StringUtils.isBlank(content[0])) {
                validationMsg.append("●文件中第" + (i + 1) + "行不能为空。<br/>");
                continue;
            }

            MachineinfoEntity machineinfoEntity = new MachineinfoEntity();
            machineinfoEntity.setId(id);
            machineinfoEntityList.add(machineinfoEntity);
        }

        if (!StringUtils.isBlank(validationMsg.toString())) {
            throw new ValidationException(validationMsg.toString());
        }
        return machineinfoEntityList;
    }

    public List<String> findModuleList(Long userId) {
        return machineinfoDao.findModuleList(userId);
    }

    public List<MachineinfoEntity> findHostListByModule(Long userId, String moduleName) {
        return machineinfoDao.findHostListByModule(userId, moduleName);
    }

    public MachineinfoEntity findMachineByMachineId(Long userId, Long machineId, String moduleName) {
        return machineinfoDao.findMachineByMachineId(userId, machineId, moduleName);
    }
}
